Skip to content

Conversation

@TomasVotruba
Copy link
Member

@TomasVotruba TomasVotruba commented Jan 27, 2026

PHPUnit 12 introduced requirement for mocks to be used or be stubs. There is quite common use case that breaks this assumption. Mock object defined in in setUp() method, used in multiple test methods, but not defining expectations in all of them. Often these mocks are passed as arguments into a new service defined in setUp() method as well.

This will turn your PHPUnit run into list of NNNNNNs and make test hard to read and impossible to turn off. It seem something is broken, and it forces you to rewrite a lot of tests manually.

Since PHPUnit 12.5.2 you can add special attribute per tests to ignore this notice. More manual dumb work.

This rule automates this process by looking at:

  • is there a MockObject property? ✔️
  • is there a setUp() method? ✔️
  • are there at leats 2 test methods? ✔️
  • is the mock property used either in setUp() method or at least in 2 tests methods? - TODO

Then adds the attribute there, as we obviously want to use the mock this way.


Any further checks we can automate? Keep them coming.

+#[\PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations]
final class SomeClass extends TestCase
{
    private \PHPUnit\Framework\MockObject\MockObject $someMock;

    protected function setUp(): void
    {
        $this->someMock = $this->createMock(\stdClass::class);
    }

    public function testOne()
    {
    }

    public function testTwo()
    {

    }
}

@TomasVotruba TomasVotruba force-pushed the tv-allow-attribute branch 4 times, most recently from dd60750 to 7bc815c Compare January 27, 2026 14:00
@TomasVotruba TomasVotruba force-pushed the tv-allow-attribute branch 2 times, most recently from 51203a3 to 287fca2 Compare January 28, 2026 15:52
@TomasVotruba TomasVotruba merged commit db0d1d5 into main Jan 28, 2026
7 checks passed
@TomasVotruba TomasVotruba deleted the tv-allow-attribute branch January 28, 2026 16:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants